package com.yuke.cloud.service.cmc.controller.frontend;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yuke.cloud.common.core.support.BaseController;
import com.yuke.cloud.common.util.wrapper.WrapMapper;
import com.yuke.cloud.common.util.wrapper.Wrapper;
import com.yuke.cloud.service.api.cmc.dto.CmsCouponUserDto;
import com.yuke.cloud.service.cmc.entity.CmsCoupon;
import com.yuke.cloud.service.cmc.entity.CmsCouponReceive;
import com.yuke.cloud.service.cmc.service.CmsCouponReceiveService;
import com.yuke.cloud.service.cmc.service.CmsCouponService;
import com.yuke.cloud.service.cmc.service.CmsCouponSpecService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.Synchronized;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
* Created by wg on 2019/09/25.
*/
@Api(value = "WEB - CmsCouponReceiveController", tags = "处理CmsCouponReceive相关请求", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RestController
@RequestMapping("/cms/coupon_receive")
public class CmsCouponReceiveController extends BaseController {
    @Resource
    private CmsCouponReceiveService cmsCouponReceiveService;

    @Resource
    private CmsCouponService cmsCouponService;

    @Resource
    private CmsCouponSpecService cmsCouponSpecService;

    @PostMapping
    @ApiOperation(httpMethod = "POST", value = "新增一条记录")
    public Wrapper add(@ApiParam(name = "cmsCouponReceive", value = "该数据记录的POJO") @RequestBody CmsCouponReceive cmsCouponReceive) {
        cmsCouponReceive.setReferer(getLoginAuthDto().getUserId().toString());
        cmsCouponReceiveService.save(cmsCouponReceive);
        return WrapMapper.ok();
    }

    @DeleteMapping("/{id}")
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除一条记录")
    public Wrapper delete(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {
        cmsCouponReceiveService.deleteById(id);
        return WrapMapper.ok();
    }

    @PutMapping
    @ApiOperation(httpMethod = "PUT", value = "修改一条记录")
    public Wrapper update(@ApiParam(name = "cmsCouponReceive", value = "需要修改的内容") @RequestBody CmsCouponReceive cmsCouponReceive) {
        cmsCouponReceive.setReferer(getLoginAuthDto().getUserId().toString());
        cmsCouponReceiveService.update(cmsCouponReceive);
        return WrapMapper.ok();
    }

    @GetMapping("/{id}")
    @ApiOperation(httpMethod = "GET", value = "根据ID获取具体信息")
    public Wrapper<CmsCouponReceive> detail(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {
        CmsCouponReceive cmsCouponReceive = cmsCouponReceiveService.findById(id);
        return WrapMapper.ok(cmsCouponReceive);
    }

    @GetMapping
    @ApiOperation(httpMethod = "GET", value = "分页获取所有记录")
    public Wrapper<PageInfo<CmsCouponReceive>> list(@ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                                    @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size) {
        PageHelper.startPage(page, size);
        List<CmsCouponReceive> list = cmsCouponReceiveService.findAll();
        PageInfo pageInfo = new PageInfo(list);
        return WrapMapper.ok(pageInfo);
    }

    @PostMapping("/selectCouponReceive")
    @ApiOperation(httpMethod = "POST", value = "分页获取所有记录")
    public Wrapper<PageInfo<CmsCouponUserDto>> list(
    @ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
    @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size,
                                                   @RequestBody CmsCouponUserDto cmsCouponReceive ) {
        PageHelper.startPage(page, size);
        List<CmsCouponUserDto> list = cmsCouponReceiveService.getCouponUserListByCondition(cmsCouponReceive);
        PageInfo pageInfo = new PageInfo(list);
        if (list == null && list.size() < 1){
            return WrapMapper.ok(pageInfo);
        }

        list = cmsCouponReceiveService.addShopInfo(list);
        pageInfo.setList(list);
        return WrapMapper.ok(pageInfo);
    }

    //通过优惠券id查找领券信息
    @GetMapping("/couponId/{couponId}")
    @ApiOperation(httpMethod = "GET", value = "分页获取所有记录")
    public Wrapper<PageInfo<CmsCouponUserDto>> getUserlistBycouponId(@ApiParam(name = "pageUserList", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                                    @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size,
                                                    @PathVariable Long couponId) {
        PageHelper.startPage(page, size);
        CmsCouponUserDto cmsCouponReceive = new CmsCouponUserDto();
        cmsCouponReceive.setCouponId(couponId);
        List<CmsCouponUserDto> list = cmsCouponReceiveService.getCouponUserList(cmsCouponReceive);
        PageInfo pageInfo = new PageInfo(list);
        return WrapMapper.ok(pageInfo);
    }

    /**
     * 个人已领优惠券信息（可用的）
     * 通过shop_id查找领券信息
     * @param shopId
     * @return
     */
    @GetMapping("/shopId/{shopId}")
    @ApiOperation(httpMethod = "GET", value = "获取所有记录")
    public Wrapper<List<CmsCouponUserDto>> getUserlistByshopId(@PathVariable Long shopId) {
        System.out.println("个人已领优惠券信息（可用的）" + shopId);
        CmsCouponUserDto cmsCouponReceive = new CmsCouponUserDto();
        cmsCouponReceive.setReceiveType((byte)1);
        cmsCouponReceive.setReceiveId(shopId);
        cmsCouponReceive.setCouponStatus((byte)0);
        List<CmsCouponUserDto> list = cmsCouponReceiveService.getCouponUserList(cmsCouponReceive);
        System.out.println("个人已领优惠券信息（可用的）" + list);
        return WrapMapper.ok(list);
    }

    @GetMapping("/couponForPage")
    @ApiOperation(httpMethod = "GET", value = "获取所有记录")
    public Wrapper<PageInfo<CmsCouponUserDto>> getCouponlistByshopId(@ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                                               @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size,
                                                                 @ApiParam(name = "shopId", value = "店铺ID", defaultValue = "0") @RequestParam(defaultValue = "0")  Long shopId) {
        System.out.println("个人已领优惠券信息（可用的）" + shopId);
        PageHelper.startPage(page, size);
        CmsCouponUserDto cmsCouponReceive = new CmsCouponUserDto();
        cmsCouponReceive.setReceiveType((byte)1);
        cmsCouponReceive.setReceiveId(shopId);
        cmsCouponReceive.setCouponStatus((byte)0);
        List<CmsCouponUserDto> list = cmsCouponReceiveService.getCouponUserList(cmsCouponReceive);
        System.out.println("个人已领优惠券信息（可用的）" + list);
        PageInfo pageInfo = new PageInfo(list);
        return WrapMapper.ok(pageInfo);
    }


    //通过userId查找领券信息
    @GetMapping("/userId/{userId}")
    @ApiOperation(httpMethod = "GET", value = "获取所有记录")
    public Wrapper<List<CmsCouponUserDto>> getUserlistByUserId(@PathVariable Long userId) {
        CmsCouponUserDto cmsCouponReceive = new CmsCouponUserDto();
        cmsCouponReceive.setReceiveId(userId);
        cmsCouponReceive.setReceiveType((byte)0);
        cmsCouponReceive.setCouponStatus((byte)0);
        List<CmsCouponUserDto> list = cmsCouponReceiveService.getCouponUserList(cmsCouponReceive);

        return WrapMapper.ok(list);
    }

    @PostMapping("/getcoupon")
    @ApiOperation(httpMethod = "POST", value = "新增一条领取优惠券记录")
    @Transactional(rollbackFor = Exception.class)
    @Synchronized
    public Wrapper addCoupon(@ApiParam(name = "cmsCouponReceive", value = "该数据记录的POJO") @RequestBody CmsCouponReceive cmsCouponReceive) {

        if (cmsCouponReceive.getCouponId()!=null) {
            CmsCoupon cmsCoupon = cmsCouponService.findById(cmsCouponReceive.getCouponId());
            //检查优惠券剩余数量，领券时间
            if (cmsCoupon!=null){
                //检查是否已经领取超过限额的优惠券数量
                List<CmsCouponReceive> couponUser = cmsCouponReceiveService.select(cmsCouponReceive);
                //cmsCoupon.getNumber()==0时，无领取限制
                if (cmsCoupon.getNumber()>0){
                    if (couponUser.size() >= cmsCoupon.getMinTransmitNum()){
                        return WrapMapper.error("该优惠券只能领取"+cmsCoupon.getMinTransmitNum()+"张！");
                    }
                }

                //检查时间限制
                Date nowtime = new Date();
                if(cmsCoupon.getSendStartDate().getTime() >= nowtime.getTime()){
                    return WrapMapper.error("该优惠券还未到领取时间！");
                }
                if(cmsCoupon.getSendEndDate().getTime() <= nowtime.getTime()){
                    return WrapMapper.error("该优惠券已过期！");
                }
                if(cmsCoupon.getSendType().equals(5)){
                    return WrapMapper.error("该优惠券由系统自动派发！");
                }
                if(cmsCoupon.getSendType().equals(6)){
                    return WrapMapper.error("该优惠券由系统自动派发！");
                }
                if (cmsCoupon.getNumber()-cmsCoupon.getNowNum()>0){
                    //领取1张
                    cmsCoupon.setNowNum(cmsCoupon.getNowNum()+1);
                    cmsCouponService.update(cmsCoupon);
                    cmsCouponReceiveService.save(cmsCouponReceive);

                }else{
                    return WrapMapper.error("该优惠券已经没有了！");
                }
            }
        }else{
            return WrapMapper.error("程序错误。优惠券ID为空！");
        }
        return WrapMapper.ok("优惠券领取成功！");
    }

    @PutMapping("/getUserList")
    @ApiOperation(httpMethod = "POST", value = "获取所有记录")
    public Wrapper<List<CmsCouponUserDto>> getUserListBycondition(@RequestBody CmsCouponUserDto cmsCouponUserDto) {
        List<CmsCouponUserDto> list = cmsCouponReceiveService.getCouponUserList(cmsCouponUserDto);
        return WrapMapper.ok(list);
    }

    @DeleteMapping("/delete/{id}")
    @ApiOperation(httpMethod = "DELETE", value = "根据id删除一条记录")
    public Wrapper deleteById(@ApiParam(name = "id", value = "记录id") @PathVariable Long id) {
       // cmsCouponReceiveService.deleteById(id);
        //保留商户用券信息，只修改状态
        cmsCouponReceiveService.modifyCouponStatus(id,0L);
        return WrapMapper.ok();
    }

    @GetMapping("/affiliate")
    @ApiOperation(httpMethod = "GET", value = "分页获取优惠券被领取信息")
    public Wrapper<PageInfo<CmsCouponUserDto>> getUserCouponReceive(@ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                                                   @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size) {

        PageHelper.startPage(page, size);
        List<CmsCouponUserDto> list = cmsCouponReceiveService.getCouponAffiliateList();
        PageInfo pageInfo = new PageInfo(list);
        return WrapMapper.ok(pageInfo);
    }

    public List<CmsCouponUserDto> getCouponListByReceiveId(@RequestParam(value = "shopId") Long shopId,@RequestParam(value = "shopId") Integer sendAspect){
        return cmsCouponReceiveService.getCouponListByReceiveId(shopId,sendAspect);
    }

    @GetMapping("/details/{couponId}")
    @ApiOperation(httpMethod = "GET", value = "分页获取优惠券被领取详情")
    public Wrapper<PageInfo<CmsCouponUserDto>> getCouponDetails(@PathVariable(value = "couponId") Long couponId,
                                                                     @ApiParam(name = "page", value = "分页值", defaultValue = "0") @RequestParam(defaultValue = "0") Integer page,
                                                                     @ApiParam(name = "size", value = "每分页返回的记录数", defaultValue = "0") @RequestParam(defaultValue = "0") Integer size) {

        PageHelper.startPage(page, size);
        List<CmsCouponUserDto> list = cmsCouponReceiveService.getCouponDetails(couponId);
        PageInfo pageInfo = new PageInfo(list);
        return WrapMapper.ok(pageInfo);

    }

}
